const { app, BrowserWindow } = require('electron');
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');
var logger = require('morgan');
var fs = require('fs');
const url = require('url');
const {PRIVATE_KEY} = require('./utils/constant')
var cookieParser = require('cookie-parser');
const expressJWT = require('express-jwt')
var usersRouter=require('./route/users')
var loginRouter=require('./route/login')
const TcpSocketServer = require('./utils/tcpSocketServer');
const WebSocketServer = require('./utils/webSocketServer');
const tcpSocketServer = new TcpSocketServer();
const webSocketServer = new WebSocketServer();
tcpSocketServer.setWebSocketServer(webSocketServer);
webSocketServer.setTcpServer(tcpSocketServer);

const os = require('os');
const networkInterfaces = os.networkInterfaces();
const setupLogging = require('./utils/logToFile');
setupLogging();

// 检查文件夹是否存在
if (!fs.existsSync("logs")) {
  // 如果不存在，则创建文件夹
  fs.mkdirSync("logs");
  console.log('文件夹已创建：', "logs");
} else {
  console.log('文件夹已存在：', "logs");
}

// 创建Express服务器
const appExpress = express();
const logFilePath = path.join(__dirname, 'logs','app.log');
var accesLogStream = fs.createWriteStream(logFilePath, { flags: 'a' });
appExpress.use(cors());
appExpress.use(cookieParser());
appExpress.use(bodyParser.json());
const logFormat = ':date[iso] :method :url :status :response-time ms';
appExpress.use(logger(logFormat,{stream: accesLogStream }));
appExpress.use(express.urlencoded({ extended: false }));
// 拦截器
appExpress.use(expressJWT({
  secret: PRIVATE_KEY
}).unless({
  path: ['/api/register','/api/login','/api/users/page','/api/refreshOnline']  //白名单,除了这里写的地址，其他的URL都需要验证
}));
appExpress.use('/api/users',usersRouter)
appExpress.use('/api',loginRouter)
appExpress.use(express.static(path.join(__dirname, 'dist')));
appExpress.get('/', (req, res) => {
  res.send('Hello World!')
})

appExpress.get('/api/refreshOnline', (req, res) => {
  const devices = tcpSocketServer.getOnlineDeviceIds()
  res.json({ code: 200, msg: '成功!',data: devices });
});

appExpress.get('/api/openSocket', (req, res) => {
  tcpSocketServer.start().then(re => {
    res.json({ code: 200, msg: '启动成功!' });
  }).catch(err => {
    res.json({ code: -1, msg: err });
  });
});
appExpress.get('/api/closeSocket', (req, res) => {
  const deviceIds = tcpSocketServer.getOnlineDeviceIds();
  if (deviceIds.length > 0) {
    res.json({ code: 200, msg: '关闭成功!', data: deviceIds.length });
  } else {
    tcpSocketServer.stop().then(re => {
      res.json({ code: 200, msg: '关闭成功!' });
    }).catch(err => {
      res.json({ code: -1, msg: err });
    });
  }
});

appExpress.get('/api/forceCloseSocket', (req, res) => {
  tcpSocketServer.stop().then(re => {
    res.json({ code: 200, msg: '关闭成功!' });
  }).catch(err => {
    res.json({ code: -1, msg: err });
  });
});

appExpress.use(function(err, req, res, next) {
  console.log(err)
  if (err.name === 'UnauthorizedError') {
    //  这个需要根据自己的业务逻辑来处理
    res.status(401).send({code:-1,msg:'token验证失败'});
  }else{
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
  }
});
appExpress.listen(3000, () => {
  console.log('Express server listening on port 3000');
  tcpSocketServer.start();
  webSocketServer.start(8889);
  for (const interfaceName in networkInterfaces) {
    const addresses = networkInterfaces[interfaceName].filter(address => address.family === 'IPv4' && !address.internal);
    if (addresses.length > 0) {
      console.log(`本机的IP地址是： ${addresses[0].address}`);
      break;
    }
  }
});


function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 960,
    height: 600,
    maxHeight: 1080,
    maxWidth: 1920,
    minHeight: 600,
    minWidth: 960,
    resizable: true,//是否允许用户改变窗口的大小
    title: 'Electron Vue',
    autoHideMenuBar: true, // 隐藏导航栏
    webPreferences: {
      nodeIntegration: true
    }
  });

  // 加载Vue页面
  mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'dist', 'index.html'),
    protocol: 'file:',
    slashes: true
  }));

  //mainWindow.webContents.openDevTools();
}

app.on('ready', createWindow);
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});
